﻿
Option Explicit On
'*******************************************************************
' Program: pkgVisio
' Author: Albert E Edlund
' Date:
'
' Purpose: the pagesheet is used in the Shape and the pages
'
'*******************************************************************


#Region " imports "

Imports System
Imports System.Object
Imports System.IO
Imports System.IO.TextReader
' need to reference windowsbase in .net
Imports System.IO.Packaging

' need for dbconnectionstringbuilder used in clsConnections
Imports System.Data.Common

Imports System.Windows
Imports System.Windows.Forms
Imports System.Text.StringBuilder

Imports Microsoft.VisualBasic

Imports System.Text
Imports System.Collections
Imports System.Collections.Generic
Imports System.Collections.ObjectModel

Imports System.Xml
Imports System.Linq
Imports System.Linq.Enumerable
Imports System.Windows.Input

Imports System.Xml.Serialization
Imports System.Xml.Linq
Imports System.Xml.XPath

Imports ADODB
Imports System.Data
Imports System.Data.OleDb
Imports System.Data.Sql


Imports Microsoft.Practices.EnterpriseLibrary.Common
Imports Microsoft.Practices.EnterpriseLibrary.ExceptionHandling
Imports Microsoft.Practices.EnterpriseLibrary.ExceptionHandling.Logging



' visio v15 does not use a xName prefix which may put it into conflict with other open office apps
Imports <xmlns="http://schemas.microsoft.com/office/visio/2012/main">
Imports <xmlns:rs="urn:schemas-microsoft-com:rowset">

' generic namespace for office open xml, used in all of them
Imports <xmlns:r="http://schemas.openxmlformats.org/officeDocument/2006/relationships">


Imports pkgVisio.clsVisPackage
Imports System.Data.SqlClient
Imports pkgVisio.clsStructures
Imports pkgVisio.clsShape

#End Region




'**********************************************************************************
'
'**********************************************************************************
'



Public Class frmShape

#Region " Properties and Declarations "

    '
    ' what is the latest document
    '
    Public _xDoc As XDocument
    Public Property xDoc As XDocument
        Get
            Return Me._xDoc
        End Get
        Set(value As XDocument)
            If (value Is Nothing) Then
                Throw New System.ArgumentNullException("Value", _
                    "xDoc is Null.")
            End If
            Me._xDoc = value
        End Set
    End Property

    '
    '
    '
    Public m_visPackage As clsVisPackage
    Public Property visPackage As clsVisPackage
        Get
            visPackage = Me.m_visPackage
        End Get
        Set(value As clsVisPackage)
            If (value Is Nothing) Then
                Throw New System.ArgumentNullException("Value", _
                    "visPackage is Null.")
            End If
            Me.m_visPackage = value
        End Set
    End Property

    '
    '
    '
    Private m_visShape As clsShape
    Public Property visShape As clsShape
        Get
            visShape = Me.m_visShape
        End Get
        Set(value As clsShape)
            Me.m_visShape = value
        End Set
    End Property


    '
    '
    '
    Private m_strShapeType As String
    Public Property strShapeType As String
        Get
            strShapeType = Me.m_strShapeType
        End Get
        Set(value As String)
            Me.m_strShapeType = value
            Me.txtShapeType.Text = value
        End Set
    End Property



    '
    '
    '
    Private m_currShp As stcPageShape
    Public Property currShp As stcPageShape
        Get
            currShp = Me.m_currShp
        End Get
        Set(value As stcPageShape)
            Me.m_currShp = value
        End Set
    End Property

    '
    '
    '
    Private _strShpName As String
    Public Property strShpName As String
        Get
            strShpName = _strShpName
        End Get
        Set(value As String)
            _strShpName = value
        End Set
    End Property

    '
    '
    '
    Private _strShpNameU As String
    Public Property strShpNameU As String
        Get
            strShpNameU = _strShpNameU
        End Get
        Set(value As String)
            _strShpNameU = value
            Me.txtNameU.Text = value
        End Set
    End Property

    '
    '
    '
    Private _lngShpId As Long
    Public Property lngShpId As Long
        Get
            lngShpId = _lngShpId
        End Get
        Set(value As Long)
            _lngShpId = value
        End Set
    End Property

    '
    '
    '
    Private _strShpType As String
    Public Property strShpType As String
        Get
            strShpType = _strShpType
        End Get
        Set(value As String)
            _strShpType = value
        End Set
    End Property



    Private _dataTable As DataTable
    Public Property dataTable As DataTable
        Get
            dataTable = Me._dataTable
        End Get
        Set(value As DataTable)
            Me._dataTable = value
        End Set
    End Property


#End Region


#Region " methods "

    '
    ' pass in a section as an xelement and look for rows
    '
    Private Sub analyzeSection(ByVal xelemSection As XElement)

        Try


            Dim qryRowInfo = From rowSel In xelemSection...<Row>
            Dim intRowCt As Integer = qryRowInfo.Count

            If intRowCt > 0 Then

                Dim newShape As clsShape = New clsShape
                Me._dataTable = newShape.analyzeSectionRows(xelemSection)

                Dim intDR As Integer = Me.dataTable.Rows.Count
                If 0 < intDR Then
                    InitializeDataGridView()
                End If

            End If


        Catch errXml As XmlException
            Dim rethrow As Boolean = ExceptionPolicy.HandleException(errXml, "Log Only Policy")
            If (rethrow) Then
                Throw
            End If
        Catch err As Exception
            Dim rethrow As Boolean = ExceptionPolicy.HandleException(err, "Log Only Policy")
            If (rethrow) Then
                Throw
            End If
        End Try

    End Sub


    '
    '
    '
    Private Sub InitializeDataGridView()
        Try
            ' Set up the DataGridView.
            With Me.dgvSection
                ' Automatically generate the DataGridView columns.
                .AutoGenerateColumns = True

                ' Set up the data source.
                BindingSource1.DataSource = Me.dataTable
                .DataSource = BindingSource1

                ' Automatically resize the visible rows.
                .AutoSizeRowsMode = _
                    DataGridViewAutoSizeRowsMode.DisplayedCellsExceptHeaders

                ' Set the DataGridView control's border.
                .BorderStyle = BorderStyle.Fixed3D

                ' Put the cells in edit mode when user enters them.
                .EditMode = DataGridViewEditMode.EditOnEnter
            End With

        Catch err As Exception
            Dim rethrow As Boolean = ExceptionPolicy.HandleException(err, "Log Only Policy")
            If (rethrow) Then
                Throw
            End If
        End Try

    End Sub


    '
    '
    '
    Public Sub initShapeData _
        (ByVal strType As String, _
         ByVal pkgNew As clsVisPackage, _
         ByVal xdocNew As XDocument,
         ByVal psShape As stcPageShape)

        Try


            Me.strShapeType = strType
            Me.visPackage = pkgNew
            Me.xDoc = xdocNew
            Me.currShp = psShape

        Catch err As Exception
            Dim rethrow As Boolean = ExceptionPolicy.HandleException(err, "Log Only Policy")
            If (rethrow) Then
                Throw
            End If
        End Try

    End Sub


#End Region

#Region " form events "


    '
    '
    '
    Private Sub ExitToolStripMenuItem_Click(sender As System.Object, e As System.EventArgs) Handles ExitToolStripMenuItem.Click
        Me.Close()
    End Sub

    '
    '
    '
    Private Sub AboutToolStripMenuItem_Click(sender As System.Object, e As System.EventArgs) Handles AboutToolStripMenuItem.Click
        frmAbout.ShowDialog()
    End Sub


    '
    '
    '
    Private Sub frmShape_FormClosed(sender As Object, e As System.Windows.Forms.FormClosedEventArgs) Handles Me.FormClosed

        Me._xDoc = Nothing
        Me.m_visPackage = Nothing
        Me.m_strShapeType = ""
        Me._strShpNameU = ""
        Me.txtNameU.Text = ""
        Me.txtShapeType.Text = ""
        Me.lvShpAttr.Clear()
        Me.lvShpElem.Clear()
        Me.tvShapes.Nodes.Clear()


    End Sub

    '
    '
    '
    Private Sub frmShape_Shown(sender As Object, e As System.EventArgs) Handles Me.Shown

        Try


            Me.lvShpAttr.Clear()
            Me.lvShpElem.Clear()
            Me.tvShapes.Nodes.Clear()

            Me.visPackage.loadShapes(Me.xDoc)


            Dim qryShapeInfo As System.Collections.Generic.IEnumerable(Of System.Xml.Linq.XElement) = Nothing
            Select Case LCase(strShapeType)
                Case "shape"
                    ' need to load strShpNameU ahead of the form
                    Me.visPackage.buildTvShapes(Me.tvShapes, strShpNameU)
                    Me.lngShpId = currShp.psShape
                    qryShapeInfo = From shpSel In Me.xDoc...<Shape> _
                        Where shpSel.@ID = CStr(currShp.psShape)
                Case "pagesheet"
                    qryShapeInfo = Me.xDoc...<PageSheet>
                Case "documentsheet"
                    qryShapeInfo = Me.xDoc...<DocumentSheet>
            End Select

            Dim tempDoc As XDocument = Nothing
            If qryShapeInfo.Count = 1 Then
                Using stringReader As New StringReader(qryShapeInfo.First.ToString)
                    tempDoc = XDocument.Load(XmlReader.Create(stringReader))
                    Me.visPackage.readAttAndElem(tempDoc, "", strShapeType)
                    Me.visPackage.loadAttElemLV(Me.lvShpAttr, Me.visPackage.attDict)
                    Me.visPackage.loadAttElemLV(Me.lvShpElem, Me.visPackage.elemDict)
                End Using
            End If ' test for query count

            Me._dataTable = Nothing
            Me.dataTable = New DataTable
            Me.dgvSection.DataSource = Nothing

        Catch errXml As XmlException
            Dim rethrow As Boolean = ExceptionPolicy.HandleException(errXml, "Log Only Policy")
            If (rethrow) Then
                Throw
            End If
        Catch err As Exception
            Dim rethrow As Boolean = ExceptionPolicy.HandleException(err, "Log Only Policy")
            If (rethrow) Then
                Throw
            End If
        End Try

    End Sub

    '
    '
    '
    Private Sub tvShapes_AfterSelect(sender As Object, e As System.Windows.Forms.TreeViewEventArgs) Handles tvShapes.AfterSelect


        Try

            Me.txtNameU.Text = e.Node.Text
            Me.txtShapeType.Text = "Shape"
            Me.lvShpAttr.Clear()
            Me.lvShpElem.Clear()
            Me.dgvSection.DataSource = Nothing


            Dim newShape As stcShapeInfo = Nothing
            If e.Node Is tvShapes.TopNode Then
                newShape = Me.visPackage.dictPageShape(Me.currShp)
            Else
                newShape = CType(e.Node.Tag, stcShapeInfo)
            End If
            Dim tempDoc As XDocument = Nothing

            Me.lngShpId = newShape.lngShpId
            Me.strShpName = newShape.strShpName
            Me.strShpNameU = newShape.strShpNameU
            Me.txtNameU.Text = newShape.strShpNameU

            ' go find a shape with an ID 
            Dim qryShapeInfo = From shpSel In Me.xDoc...<Shape> _
                Where shpSel.@ID = CStr(newShape.lngShpId)

            If qryShapeInfo.Count = 1 Then
                Using stringReader As New StringReader(qryShapeInfo.First.ToString)

                    tempDoc = XDocument.Load(XmlReader.Create(stringReader))
                    Me.visPackage.readAttAndElem(tempDoc, "", "Shape")
                    Me.visPackage.loadAttElemLV(Me.lvShpAttr, Me.visPackage.attDict)
                    Me.visPackage.loadAttElemLV(Me.lvShpElem, Me.visPackage.elemDict)

                End Using
            End If ' test for query count


        Catch errXml As XmlException
            Dim rethrow As Boolean = ExceptionPolicy.HandleException(errXml, "Log Only Policy")
            If (rethrow) Then
                Throw
            End If
        Catch err As Exception
            Dim rethrow As Boolean = ExceptionPolicy.HandleException(err, "Log Only Policy")
            If (rethrow) Then
                Throw
            End If
        End Try
    End Sub


    '
    '
    '
    Private Sub lvShpElem_SelectedIndexChanged(sender As System.Object, e As System.EventArgs) Handles lvShpElem.SelectedIndexChanged



        Dim shpelemIndices As ListView.SelectedIndexCollection = Me.lvShpElem.SelectedIndices
        Dim shpelemItems As ListView.SelectedListViewItemCollection = Me.lvShpElem.SelectedItems
        Dim shpelemItem As ListViewItem
        Dim tempElement As XElement = Nothing

        ' parse out the elem name
        If shpelemItems.Count > 0 Then
            shpelemItem = shpelemItems(0)
        Else
            Exit Sub
        End If


        Dim strElemName As String = shpelemItem.SubItems(0).Text
        Dim instance As String = strElemName
        Dim charSeparators() As Char = {"_"c}
        Dim options As StringSplitOptions = StringSplitOptions.None
        Dim returnValue As String()
        Dim count As Integer = 3

        returnValue = instance.Split(charSeparators, _
                count, options)


        Me.dgvSection.DataSource = Nothing

        Try

            If 0 < shpelemItems.Count Then

                Dim qrySheet As System.Collections.Generic.IEnumerable(Of System.Xml.Linq.XElement) = Nothing
                Select Case LCase(strShapeType)
                    Case "shape"
                        qrySheet = From shpSel In Me.xDoc...<Shape>
                           Where shpSel.@ID = CStr(Me.lngShpId)
                        Dim intShapes As Integer = qrySheet.Count
                    Case "pagesheet"
                        qrySheet = Me.xDoc...<PageSheet>
                    Case "documentsheet"
                        qrySheet = Me.xDoc...<DocumentSheet>
                End Select

                For Each shape In qrySheet

                    ' get the objects elements
                    Dim listOfElements As IEnumerable(Of XElement) = _
                            From elem In shape.Elements() _
                            Select elem
                    For Each elem As XElement In listOfElements
                        If returnValue.Length = 2 Then
                            If LCase(elem.Name.LocalName) = LCase(returnValue(0)) _
                                And LCase(elem.@N) = LCase(returnValue(1)) Then
                                tempElement = elem
                                GoTo FoundShapeElement
                            End If
                        End If
                        ' because some sections can have multiples, we included the index (as appropriate)
                        If returnValue.Length = 3 Then
                            If (LCase(elem.Name.LocalName) = LCase(returnValue(0))) _
                                And (LCase(elem.@N) = LCase(returnValue(1))) _
                                And (LCase(elem.@IX) = CStr(returnValue(2))) Then
                                tempElement = elem
                                GoTo FoundShapeElement
                            End If
                        End If
                    Next elem
                Next shape
            End If ' test that something has been selected

FoundShapeElement:
            ' examine sections
            If returnValue(0) = "section" _
                And tempElement IsNot Nothing Then
                analyzeSection(tempElement)
            End If

        Catch errXml As XmlException
            Dim rethrow As Boolean = ExceptionPolicy.HandleException(errXml, "Log Only Policy")
            If (rethrow) Then
                Throw
            End If
        Catch err As Exception
            Dim rethrow As Boolean = ExceptionPolicy.HandleException(err, "Log Only Policy")
            If (rethrow) Then
                Throw
            End If
        End Try


    End Sub



#End Region


    '
    '
    '
    Public Sub New()

        ' This call is required by the designer.
        InitializeComponent()

        ' Add any initialization after the InitializeComponent() call.

        Me.m_visPackage = Nothing
        Me.m_visPackage = New clsVisPackage

        Me._xDoc = Nothing
        Me._xDoc = New XDocument

        Me.m_strShapeType = "shape"
        Me._strShpNameU = ""


        Me.lvShpAttr.Clear()
        Me.lvShpElem.Clear()



        Me._dataTable = Nothing
        Me.dataTable = New DataTable
        Me.dgvSection.DataSource = Nothing


    End Sub


End Class